package edu.sias.course.utils;
import edu.sias.course.constants.SubjectConstants;
import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;


import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 创建学科es工具类
 */
@Component
public class Esinterutils {

    private RestHighLevelClient client;
    private static final Logger logger = LoggerFactory.getLogger(Esinterutils.class);

    /**
     * 初始化客户端（可配置化改造后应从配置读取 host）
     */

    private void init() {
        this.client = new RestHighLevelClient(
                RestClient.builder(HttpHost.create("http://115.29.161.73:9200"))
        );
    }

    /**
     * 创建索引库
     */
    public void createIndexMAPPING(String index) throws IOException {
      init();
        // 1. 创建Request对象
        org.elasticsearch.client.indices.CreateIndexRequest request = new CreateIndexRequest("coursecontent");

        // 2. 请求参数, MAPPING_TEMPLATE 是静态常量字符串, 内容是创建索引库的DSL语句
        request.source(SubjectConstants.Department_Contents, XContentType.JSON);

        // 3. 发起请求
        client.indices().create(request, RequestOptions.DEFAULT);
        destroy();
    }
/// 删除索引库
    public void deleteIndex() throws IOException {
        init();
        DeleteIndexRequest request = new DeleteIndexRequest("coursecontent");

        try {
            AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
            if (response.isAcknowledged()) {
                System.out.println("索引 [" + "coursecontent" + "] 删除成功");
            }
        } catch (IOException | ElasticsearchException e) {
            e.printStackTrace();
        } finally {
            destroy();
        }
    }



    /* * 插入文档到指定索引
     *
     * @param index 索引名称
     * @param id    文档ID
     * @param text  要插入的文本内容
     */

    /**
     * 插入文档到指定索引
     *
     * @param index 索引名称
     * @param id    文档ID
     * @param title 标题
     */
    public void add( String id, String title, String content) throws IOException {
        init();
        try {
            XContentBuilder contentBuilder = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("title", title)
                    .field("content", content)
                    .endObject();

            IndexRequest request = new IndexRequest("coursecontent")
                    .id(id)
                    .source(contentBuilder);

            client.index(request, RequestOptions.DEFAULT);
            System.out.println("文档已插入");
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            destroy();
        }
    }

    /**
     * 根据ID查询文档
     *
     * @param  索引名称
     * @param id    文档ID
     * @return 返回文档内容（JSON 字符串），如果不存在则返回 null
     */
    public Map<String, Object> getById( String id) throws IOException {
        init();
        GetRequest request = new GetRequest("coursecontent", id);
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        destroy();
        if (response.isExists()) {
            return response.getSourceAsMap();
        } else {
            return null; // 文档不存在
        }

    }

    /**
     * 根据 ID 删除文档
     *
     * @param 索引名称
     * @param id    文档 ID
     * @return 是否删除成功
     */
    public boolean deleteById( String id) throws IOException {
        init();
        try {
            DeleteRequest request = new DeleteRequest("coursecontent", id);
            client.delete(request, RequestOptions.DEFAULT);
            logger.info("文档删除成功：index={}, id={}", "coursecontent", id); // 这行应输出到控制台/日志文件
            return true;
        } catch (IOException e) {
            logger.error("文档删除失败：index={}, id={}", "coursecontent", id, e);
            throw e;
        } finally {
            destroy();
        }
    }



    /**
     * 销毁客户端（释放资源）
     */

    private void destroy() {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


